package com.study;

import com.study.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-13 13:09
 * @version: 1.0
 * @description: 环形链表
 * 给你一个链表，判断链表中是否有环
 **/
public class LinkCycle {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1, null);
        ListNode node2 = new ListNode(2, node1);
        ListNode node3 = new ListNode(3, node2);
        ListNode node4 = new ListNode(4, node3);
        ListNode node5 = new ListNode(5, node4);
//        node1.next = node4;
        System.out.println(hasCycle(node5));
        System.out.println(hasCycle2(node5));
    }

    /*
    双指针解法 不占用额外空间，时间复杂度为 O(n)
    定义 快慢指针
     */
    private static boolean hasCycle2(ListNode head) {
        if (head == null || head.next == null){
            return false;
        }

        ListNode slow = head;
        ListNode quick = head.next;

        while (slow != quick){
            if (quick == null || quick.next == null){
                return false;
            }
            slow = slow.next;
            quick = quick.next.next;
        }
        return true;
    }
    private static boolean hasCycle22(ListNode head){
        if(head == null || head.next == null){
            return false;
        }
        //定义快慢指针
        ListNode slow = head;
        ListNode quick = head.next;
        while (quick!=null && quick.next != null){
            if (quick == slow) return  true;
            slow = slow.next;
            quick = quick.next.next;
        }
        return false;
    }
    /**
     * 传统解法 时间复杂度和空间复杂度都是 O(n)
     * @param head
     * @return
     */
    private static boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while (head != null ){
            if (!set.add(head)) {
                return true;
            }
           head = head.next;
        }
        return false;
    }
}
